/**
 * 主要JavaScript文件 - 科技风格个人网站
 */

document.addEventListener('DOMContentLoaded', function() {
    // 初始化所有功能
    initScrollEffects();
    initNavbarEffects();
    initCardAnimations();
    initTypingEffect();
    initLoginModal();
});

/**
 * 初始化滚动效果
 */
function initScrollEffects() {
    const navbar = document.querySelector('.tech-nav');
    
    window.addEventListener('scroll', function() {
        if (window.scrollY > 50) {
            navbar.style.background = 'rgba(10, 10, 10, 0.98)';
            navbar.style.boxShadow = '0 2px 20px rgba(0, 212, 255, 0.1)';
        } else {
            navbar.style.background = 'rgba(10, 10, 10, 0.95)';
            navbar.style.boxShadow = 'none';
        }
    });
    
    // 滚动时显示元素动画
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };
    
    const observer = new IntersectionObserver(function(entries) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('fade-in-up');
            }
        });
    }, observerOptions);
    
    // 观察所有卡片元素
    document.querySelectorAll('.tech-card, .article-card').forEach(card => {
        observer.observe(card);
    });
}

/**
 * 初始化导航栏效果
 */
function initNavbarEffects() {
    const navLinks = document.querySelectorAll('.navbar-nav .nav-link');
    
    navLinks.forEach(link => {
        link.addEventListener('mouseenter', function() {
            this.style.textShadow = '0 0 10px rgba(0, 212, 255, 0.5)';
        });
        
        link.addEventListener('mouseleave', function() {
            this.style.textShadow = 'none';
        });
    });
}

/**
 * 初始化卡片动画效果
 */
function initCardAnimations() {
    const cards = document.querySelectorAll('.tech-card, .article-card');
    
    cards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-10px) scale(1.02)';
        });
        
        card.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0) scale(1)';
        });
    });
}

/**
 * 初始化打字机效果
 */
function initTypingEffect() {
    const typingElement = document.querySelector('.typing-effect');
    if (!typingElement) return;
    
    const texts = [
        '全栈开发者',
        '技术分享者',
        '开源爱好者',
        '终身学习者'
    ];
    
    let textIndex = 0;
    let charIndex = 0;
    let isDeleting = false;
    
    function typeText() {
        const currentText = texts[textIndex];
        
        if (isDeleting) {
            typingElement.textContent = currentText.substring(0, charIndex - 1);
            charIndex--;
        } else {
            typingElement.textContent = currentText.substring(0, charIndex + 1);
            charIndex++;
        }
        
        let typeSpeed = isDeleting ? 100 : 200;
        
        if (!isDeleting && charIndex === currentText.length) {
            typeSpeed = 2000; // 暂停时间
            isDeleting = true;
        } else if (isDeleting && charIndex === 0) {
            isDeleting = false;
            textIndex = (textIndex + 1) % texts.length;
            typeSpeed = 500;
        }
        
        setTimeout(typeText, typeSpeed);
    }
    
    typeText();
}

/**
 * 平滑滚动到指定元素
 */
function smoothScrollTo(elementId) {
    const element = document.getElementById(elementId);
    if (element) {
        element.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        });
    }
}

/**
 * 复制代码到剪贴板
 */
function copyCode(button) {
    const codeBlock = button.nextElementSibling.querySelector('code');
    const text = codeBlock.textContent;
    
    navigator.clipboard.writeText(text).then(function() {
        button.textContent = '已复制!';
        button.style.background = '#28a745';
        
        setTimeout(function() {
            button.textContent = '复制代码';
            button.style.background = '';
        }, 2000);
    });
}

/**
 * 搜索功能
 */
function initSearch() {
    const searchInput = document.querySelector('#search-input');
    const searchResults = document.querySelector('#search-results');
    
    if (!searchInput) return;
    
    let searchTimeout;
    
    searchInput.addEventListener('input', function() {
        clearTimeout(searchTimeout);
        const query = this.value.trim();
        
        if (query.length < 2) {
            searchResults.innerHTML = '';
            return;
        }
        
        searchTimeout = setTimeout(() => {
            performSearch(query);
        }, 300);
    });
}

/**
 * 执行搜索
 */
function performSearch(query) {
    // 这里可以实现实际的搜索逻辑
    // 可以是前端搜索或者AJAX请求后端API
    console.log('搜索:', query);
}

/**
 * 主题切换功能（预留）
 */
function toggleTheme() {
    const body = document.body;
    const currentTheme = body.getAttribute('data-theme');
    
    if (currentTheme === 'light') {
        body.setAttribute('data-theme', 'dark');
        localStorage.setItem('theme', 'dark');
    } else {
        body.setAttribute('data-theme', 'light');
        localStorage.setItem('theme', 'light');
    }
}

/**
 * 加载保存的主题
 */
function loadSavedTheme() {
    const savedTheme = localStorage.getItem('theme') || 'dark';
    document.body.setAttribute('data-theme', savedTheme);
}

// 页面加载时应用保存的主题
loadSavedTheme();

/**
 * 初始化登录弹窗功能
 */
function initLoginModal() {
    // 获取CSRF token
    function getCSRFToken() {
        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]');
        return csrfToken ? csrfToken.value : '';
    }
    
    // 显示登录弹窗
    function showLoginModal() {
        console.log('showLoginModal 函数被调用');
        const loginModalElement = document.getElementById('loginModal');
        console.log('登录弹窗元素:', loginModalElement);
        console.log('Bootstrap 可用性:', typeof bootstrap !== 'undefined');
        
        if (loginModalElement && typeof bootstrap !== 'undefined') {
            try {
                const loginModal = new bootstrap.Modal(loginModalElement);
                console.log('Bootstrap Modal 实例创建成功:', loginModal);
                loginModal.show();
                console.log('调用 modal.show() 完成');
            } catch (error) {
                console.error('创建或显示 Bootstrap Modal 时出错:', error);
            }
        } else {
            console.error('登录弹窗元素或Bootstrap未找到');
            if (!loginModalElement) {
                console.error('未找到 ID 为 loginModal 的元素');
            }
            if (typeof bootstrap === 'undefined') {
                console.error('Bootstrap 未加载');
            }
        }
    }
    
    // 隐藏登录弹窗
    function hideLoginModal() {
        const loginModalElement = document.getElementById('loginModal');
        if (loginModalElement && typeof bootstrap !== 'undefined') {
            const loginModal = bootstrap.Modal.getInstance(loginModalElement);
            if (loginModal) {
                loginModal.hide();
            }
        }
    }
    
    // 显示错误信息
    function showError(message) {
        const errorDiv = document.getElementById('loginError');
        const errorMessage = document.getElementById('loginErrorMessage');
        errorMessage.textContent = message;
        errorDiv.classList.remove('d-none');
    }
    
    // 隐藏错误信息
    function hideError() {
        const errorDiv = document.getElementById('loginError');
        errorDiv.classList.add('d-none');
    }
    
    // 设置按钮加载状态
    function setButtonLoading(loading) {
        const submitBtn = document.getElementById('loginSubmitBtn');
        const btnText = submitBtn.querySelector('.btn-text');
        const spinner = submitBtn.querySelector('.spinner-border');
        
        if (loading) {
            submitBtn.disabled = true;
            btnText.textContent = '登录中...';
            spinner.classList.remove('d-none');
        } else {
            submitBtn.disabled = false;
            btnText.textContent = '登录';
            spinner.classList.add('d-none');
        }
    }
    
    // 密码显示/隐藏切换
    const togglePasswordBtn = document.getElementById('togglePassword');
    const passwordInput = document.getElementById('password');
    
    if (togglePasswordBtn && passwordInput) {
        togglePasswordBtn.addEventListener('click', function() {
            const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
            passwordInput.setAttribute('type', type);
            
            const icon = this.querySelector('i');
            if (type === 'password') {
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            } else {
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            }
        });
    }
    
    // 处理登录表单提交
    const loginForm = document.getElementById('loginForm');
    if (loginForm) {
        loginForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            hideError();
            setButtonLoading(true);
            
            const formData = new FormData(this);
            const loginData = {
                username: formData.get('username'),
                password: formData.get('password'),
                remember_me: formData.get('remember_me') === 'on'
            };
            
            try {
                const response = await fetch('/auth/login/', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': getCSRFToken()
                    },
                    body: JSON.stringify(loginData)
                });
                
                const result = await response.json();
                
                if (result.success) {
                    // 登录成功，刷新页面
                    hideLoginModal();
                    window.location.reload();
                } else {
                    // 显示错误信息
                    showError(result.message || '登录失败，请重试');
                }
            } catch (error) {
                console.error('登录请求失败:', error);
                showError('网络错误，请检查网络连接后重试');
            } finally {
                setButtonLoading(false);
            }
        });
    }
    
    // 检查用户认证状态并更新UI
    async function checkAuthStatus() {
        try {
            const response = await fetch('/auth/status/');
            const result = await response.json();
            
            if (result.authenticated) {
                document.body.classList.add('authenticated');
                // 可以在这里更新导航栏显示用户信息
                updateNavbarForAuthenticatedUser(result.user);
            } else {
                document.body.classList.remove('authenticated');
            }
            return result.authenticated;
        } catch (error) {
            console.error('检查认证状态失败:', error);
            document.body.classList.remove('authenticated');
            return false;
        }
    }
    
    // 更新已认证用户的导航栏
    function updateNavbarForAuthenticatedUser(user) {
        // 这里可以添加更新导航栏的逻辑
        console.log('用户已认证:', user);
    }
    
    // 绑定登录按钮点击事件 - 直接处理登录触发器
    document.addEventListener('click', function(e) {
        console.log('点击事件触发:', e.target);
        
        // 检查是否点击了登录触发器
        const loginTrigger = e.target.closest('a[data-login-trigger="true"]') || 
                            e.target.closest('a.login-trigger');
        
        console.log('找到登录触发器:', loginTrigger);
        
        if (loginTrigger) {
            console.log('处理登录触发器点击');
            e.preventDefault();
            e.stopPropagation();
            
            // 检查当前认证状态
            const isAuthenticated = document.body.classList.contains('authenticated');
            console.log('用户认证状态:', isAuthenticated);
            
            if (!isAuthenticated) {
                console.log('显示登录弹窗');
                showLoginModal();
            } else {
                console.log('用户已认证，不显示弹窗');
            }
            return false;
        }
    }, true); // 使用捕获阶段确保优先处理
    
    // 页面加载时检查认证状态
    checkAuthStatus();
}